package com.changgou.file.controllor;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.file.pojo.FastDFSFile;
import com.changgou.file.util.FastDFSClient;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @version v1.0
 * @ProjectName: changgou_parent
 * @ClassName: FileController
 * @Description: TODO(文件上传)
 * @Author: Xu Fj
 * @Date: 2020/2/23 22:28
 */

@RestController
@RequestMapping("/file")
public class FileController {

    @PostMapping("/upload")
    public Result uploadFile(MultipartFile file) {
        try {
            //判断文件是否为空
            if (file == null) {
                throw new RuntimeException("请至少上传一个文件!");
            }
            //获取文件名
            String originalFilename = file.getOriginalFilename();
            //判断文件名不为空
            if (StringUtils.isEmpty(originalFilename)) {
                throw new RuntimeException("请至少上传一个文件!");
            }

            //获取文件的扩展名
            String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);

            //获取文件内容
            byte[] bytes = file.getBytes();

            //创建文件上传的实体类
            FastDFSFile fastDFSFile = new FastDFSFile(originalFilename, bytes, extName);

            //使用工具类上传
            String[] uploadResult = FastDFSClient.upload(fastDFSFile);

            //拼接返回结果得到完整路径
            String url = FastDFSClient.getTrackerUrl() + uploadResult[0] + "/" + uploadResult[1];
            return new Result(true, StatusCode.OK, "文件上传成功", url);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new Result(false, StatusCode.ERROR, "文件上传失败");
    }
}
